package application;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.sql.Connection;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.plugin.druid.DruidPlugin;

import application.common.mapping._MappingKit;
import application.common.util.FiltUtil;
import application.common.util.ShiroUtil;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.Parent;
import javafx.scene.Scene;

public class Main extends Application {
	
	protected DruidPlugin druidPlugin;
	protected ActiveRecordPlugin arp;
	
	@Override
	public void start(Stage primaryStage) {
		try {
			ShiroUtil.setProcessId(getProcessID());
			primaryStage.initStyle(StageStyle.UNDECORATED);// 设定窗口无边框
			Parent root = FXMLLoader.load(getClass().getResource("/application/view/MainScene.fxml"));
			Scene scene = new Scene(root);
			scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
			primaryStage.setScene(scene);
			primaryStage.show();
			ShiroUtil.setMainProcess(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	@Override
	public void init() throws Exception {
		super.init();
		String path=String.format("%sresources/cabinet.db", FiltUtil.getPath());
		druidPlugin = new DruidPlugin("jdbc:sqlite:"+path, "", "");
		druidPlugin.setDriverClass("org.sqlite.JDBC");
		arp = new ActiveRecordPlugin(druidPlugin);
		arp.setShowSql(true);
		arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
		arp.getEngine().setToClassPathSourceFactory();
		arp.setDialect(new Sqlite3Dialect());
		_MappingKit.mapping(arp);
		druidPlugin.start();
		arp.start();
	}

	@Override
	public void stop() throws Exception {
		super.stop();
		if (arp != null) {
			arp.stop();
		}
		if (druidPlugin != null) {
			druidPlugin.stop();
		}
		Runtime.getRuntime().exec("taskkill /F /PID " + ShiroUtil.getProcessId());
		System.exit(0);
	}
	
	public static final int getProcessID() {
		RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
		return Integer.valueOf(runtimeMXBean.getName().split("@")[0]).intValue();
	}

	public static void main(String[] args) {
		launch(args);
	}
}
